package com.turtle.security.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * ip地址工具类
 *
 * @author turtle
 * date: 2020-06-05
 */
@Slf4j
@Component
public class IpAddressUtils {

    private static final byte[] NO_BYTE = {};
    private static final String UNKNOWN = "unknown";
    private static final String LOCAL_IP = "127.0.0.1";
    private static final Integer NUMBER_ONE = 2;
    private static final Long NUMBER_TWO = 4294967295L;
    private static final Long NUMBER_THREE = 16777215L;
    private static final Long NUMBER_FOUR = 255L;
    private static final Long NUMBER_FIVE = 65535L;
    private static RestTemplate restTemplate = new RestTemplate();

    private static String httpServer;

    /**
     * 获取操作ip
     *
     * @param httpRequest 请求信息
     * @return ip
     */
    public static String getIpAddress(HttpServletRequest httpRequest) {
        if (CustomerStringUtils.isNull(httpRequest)) {
            return UNKNOWN;
        }

        String ip = httpRequest.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getRemoteAddr();
        }

        return "0:0:0:0:0:0:0:1".equals(ip) ? LOCAL_IP : ip;

    }

    public static boolean internalIp(String ip) {
        byte[] addr = textToNumericFormatV4(ip);
        return internalIp(addr) || LOCAL_IP.equals(ip);
    }

    private static boolean internalIp(byte[] addr) {
        if (CustomerStringUtils.isNull(addr) || addr.length < NUMBER_ONE) {
            return true;
        }
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        // 10.x.x.x/8
        final byte sectionOne = 0x0A;
        // 172.16.x.x/12
        final byte sectionTwo = (byte) 0xAC;
        final byte sectionThree = (byte) 0x10;
        final byte sectionFour = (byte) 0x1F;
        // 192.168.x.x/16
        final byte sectionFive = (byte) 0xC0;
        final byte sectionSix = (byte) 0xA8;
        switch (b0) {
            case sectionOne:
                return true;
            case sectionTwo:
                if (b1 >= sectionThree && b1 <= sectionFour) {
                    return true;
                }
            case sectionFive:
                switch (b1) {
                    case sectionSix:
                    default:
                        return false;
                }
            default:
                return false;
        }
    }

    /**
     * 将IPv4地址转换成字节
     *
     * @param text IPv4地址
     * @return byte 字节
     */
    public static byte[] textToNumericFormatV4(String text) {
        if (text.length() == 0) {
            return NO_BYTE;
        }

        byte[] bytes = new byte[4];
        String[] elements = text.split("\\.", -1);
        try {
            long l;
            int i;
            switch (elements.length) {
                case 1:
                    l = Long.parseLong(elements[0]);
                    if ((l < 0L) || (l > NUMBER_TWO)) {
                        return NO_BYTE;
                    }
                    bytes[0] = (byte) (int) (l >> 24 & 0xFF);
                    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 2:
                    l = Integer.parseInt(elements[0]);
                    if ((l < 0L) || (l > NUMBER_FOUR)) {
                        return NO_BYTE;
                    }
                    bytes[0] = (byte) (int) (l & 0xFF);
                    l = Integer.parseInt(elements[1]);
                    if ((l < 0L) || (l > NUMBER_THREE)) {
                        return NO_BYTE;
                    }
                    bytes[1] = (byte) (int) (l >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 3:
                    for (i = 0; i < NUMBER_ONE; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > NUMBER_FOUR)) {
                            return NO_BYTE;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    l = Integer.parseInt(elements[2]);
                    if ((l < 0L) || (l > NUMBER_FIVE)) {
                        return NO_BYTE;
                    }
                    bytes[2] = (byte) (int) (l >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 4:
                    for (i = 0; i < 4; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > NUMBER_FOUR)) {
                            return NO_BYTE;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    break;
                default:
                    return NO_BYTE;
            }
        } catch (NumberFormatException e) {
            return NO_BYTE;
        }
        return bytes;
    }

    /**
     * 通过ip获取操作地点
     *
     * @param ip ip号
     * @return 操作地点 省份-城市
     */
    public static String getAddressByIp(String ip) {
        String address = "内网地址";
        // 内网环境不查询
        if (internalIp(ip)) {
            return "内网地址";
        }
        // 请求高德api获取操作地址
        HttpHeaders headers = new HttpHeaders();
        HashMap<String, String> map = new HashMap<>(1);
        map.put("ip", ip);
        HttpEntity<HashMap<String, String>> request = new HttpEntity<>(map, headers);
        JSONObject res = restTemplate.postForObject(httpServer, request, JSONObject.class);

        if (res.getString("status").equals("1") && res.getString("info").equals("OK")) {
            address = res.getString("province") + res.getString("city");
        }

        return address;
    }

    @Value("${amap.http.server}")
    public void setHttpUrl(String httpServer) {
        IpAddressUtils.httpServer = httpServer;
    }

}
